import React,{Component} from 'react'
import Header from '../../component/Header'
import TextInput from '../../component/TextInput'
import Button from '../../component/Button'
import RadioCar from './RadioCar'
import { Picker, DatePicker,List } from 'antd-mobile';
import {connect} from 'react-redux'
import {StringUtils,PhoneUtils} from '../../util/bee'
import {fmtDate}  from '../../util/dateUtil'
import axios from '../../util/axios'
import {api}  from '../../api'
import './apply.scss'



class Apply extends Component{
  constructor(props){
      super(props)
      this.state = {
          //当前登录用户的id
         'applyNameId':'',
         'applyNamePhone':'',
         "userDeptId":'',
         "fwDeptID":'',
         "yongCheXz":"",
         "yongCheXzIndex":0,
         "applyQyId":1,
         "applyQyIdIndex":1,
         "applyBz":'',
         date:'',
         visible_0:false,
         visible_1:false,
         autoSetting:{
          sxrDuanhaoFlag: 0,
          sxrNameFlag: 0,
          sxrPhoneFlag: 0,
          ycrDuanhaoFlag: 0,
          ycrNameFlag: 0,
          ycrPhoneFlag: 0},
         fromItems:[
          {
            topBar: { icon: 1, title: '个人信息' },
            list: [
              { type: "InputItem",isShow:1,inputName:'yongCheRen',label: '用车人', icon:"",initValue:'', text: "", placeholder: '请填写您的真实姓名', isStar: false,isReset:true },
              { type: "InputItem",isShow:1,inputName:'applyUsePhone', label: '用车人电话',initValue:'', icon: "", text: "", placeholder: '请填写用车人电话', isStar: false ,isReset:true},
              { type: "InputItem",isShow:1,inputName:'applyManNum', label: '乘车人数', initValue:'',icon: "", text: "", placeholder: '请填写乘车人数', isStar: false  ,isReset:true}
            
           ]
          },
          {
            topBar: { icon: 2, title: '用车计划' },
            list: [
              { type: "InputItem",isShow:1,inputName:'applyDeptId',initValue:'', label: '用车单位', disabled:true,text: '',isStar: true,isReset:false},
              {
                type: "PickInputItem",isShow:1,inputName:'yongCheXz', label: '用车性质', text: '', placeholder: '', isStar: true, isReset:false,
                pickerItems: [],
              },
              //form-iconClass-addree
              { type: "InputItemDate",isShow:1,pickdateType:0,inputName:'applyUseTime',initValue:'', label: '预计出车时间',iconClass:'form-iconClass-date', text: '',placeholder:'请选择预计出车时间', isStar: true,actionType:'time',editable:false, isReset:true},
              { type: "InputItemDate",isShow:1,pickdateType:1,inputName:'applyBackTime', initValue:'',label: '预计归队时间', iconClass:'form-iconClass-date', text: '',placeholder:'请选择预计归队时间', isStar: true ,actionType:'time',editable:false, isReset:true},
              { type: "InputItem",isShow:1,inputName:'applyUseAddress', label: '出发地',inputName:'applyUseAddress',iconClass: "", text: '', placeholder: '请输入出发地', isStar: false ,actionType:'location',editable:true, isReset:true},
              { type: "InputItem",isShow:1,nputName:'applyDestination', label: '目的地', inputName:'applyDestination',iconClass:"", text: '', placeholder: '请输入目的地', isStar: false ,actionType:'map',editable:true, isReset:true},
              { type: "PickInputItem",isShow:1,inputName:'applyQyId', label: '用车区域', iconClass: "", text: "", placeholder: '', isStar: false, pickerItems: [], isReset:true },
              { type: "InputItem",isShow:1,initValue:'',label: '服务中心',disabled:true, icon: "", text: "", placeholder: '', isStar: false , isReset:false},
              { type: "InputItem",isShow:1,inputName:'applyRemark', label: '用车事由', icon:"", text: '', placeholder: '请填写用车事由', isStar: false , isReset:true}
            ]
          },
          {
            topBar: { icon: 3, title: '用车种类',type: "RadioItem"},
            list: []
          }
        ],
         postData:[
        
         //用车人
         {name:'yongCheRen',value:'',checkInfo:'用车人不能为空'},
        
          //用车人的电话
         {name:'applyUsePhone',value:'',checkInfo:'用车人的电话不能为空'},
   

         //坐车人数
         {name:'applyManNum',value:'',checkInfo:'坐车人数不能为空'},
         //开始时间
          {name:'applyUseTime',value:'',checkInfo:'开始时间不能为空'},
      
         //结束时间
         {name:'applyBackTime',value:'',checkInfo:'结束时间不能为空'},
      
         //起点
         {name:'applyUseAddress',value:'',checkInfo:'起点不能为空'},
      
         //终点
         {name:'applyDestination',value:'',checkInfo:'终点不能为空'},
         //用车事由
         {name:'applyRemark',value:'',checkInfo:'用车事由不能为空'},
         
         {name:'applyDuanhao',value:'',checkInfo:'用车人短号不能为空'},
         {name:'suiXingName',value:'',checkInfo:'随行人员不能为空'},
         {name:'suiXingPhone',value:'',checkInfo:'随行人员电话不能为空'},
         {name:'suiXingCall',value:'',checkInfo:'随行人员短号不能为空'},
      ]
       
      };
     this._changeText=this._changeText.bind(this)
     this.renderItem=this.renderItem.bind(this)
     this.postApply=this.postApply.bind(this)
     this._onCheck=this._onCheck.bind(this)

     this._onDismiss=this._onDismiss.bind(this)
     this.onOk=this.onOk.bind(this)
     this.textareaChage=this.textareaChage.bind(this)
     this.datePickerResult=this.datePickerResult.bind(this)
     this.resetAction=this.resetAction.bind(this)
    
  }
  _onCheck(number,index){
    let fromItems=this.state.fromItems;
    fromItems[2]['list'].map((item,index)=>{
       item.isCheck=false
       item.count=''
    })
    console.log("number",number);
    fromItems[2]['list'][index].count=number

    fromItems[2]['list'][index].isCheck=true;
   
    this.setState({
      fromItems
    })
     console.log(this.state.fromItems[2]['list']);
  }
  _onDismiss(e){
    console.log(e);
  }
  onOk(e,inputName){
    let fromItems=this.state.fromItems;
    
    let index=e[0];
    console.log(index);
    console.log(fromItems[1]['list'][6]['pickerItems'][index-1]);
    if(inputName=="yongCheXz"){
  
      this.setState({
        yongCheXz:fromItems[1]['list'][1]['pickerItems'][index].label,
        yongCheXzIndex:index
      }) 
    }else{
      this.setState({
        applyQyId:index,
        applyQyIdIndex:index
      }) 
    }
   console.log("this.state.applyQyIdIndex",this.state.applyQyIdIndex);
   
  }
  datePickerResult({date,pickdateType}){
   
    
    let postData=this.state.postData;
    let fromItems=this.state.fromItems;
      date=fmtDate(date);
      console.log(pickdateType)
    if(pickdateType==0){
      this.setState({ visible_0: false })
      fromItems[1]['list'][2].initValue=date
      postData[3].value=date
    }else{
      this.setState({ visible_1: false })
       fromItems[1]['list'][3].initValue=date
       postData[4].value=date
     }
   this.setState({
    fromItems,
    postData
   })
   
  }
  renderItem(item,index){
    let  {list,topBar}=item
    let inputType=null;
    console.log(list.type);
    if(topBar.type=="RadioItem"){
         inputType=<RadioCar 
         onCheck={this._onCheck}
         list={list}/>

    }else{
       inputType =list.map((sitem,index)=>{
        switch(sitem.type){
          
          case "InputItemDate":
          console.log({pickdateType:sitem.pickdateType});
          return <DatePicker
          key={index}
             mode="datetime"
             title="选择时间"
             extra="Optional"
             visible={sitem.pickdateType==0?this.state.visible_0:this.state.visible_1}
             value={this.state.date}
             onOk={(date)=>this.datePickerResult({date,pickdateType:sitem.pickdateType})}
             onDismiss={() => 
              sitem.pickdateType==0?this.setState({ visible_0: false }):this.setState({ visible_1: false })
            }
           > 
              <TextInput 
                  btnAction={() => {
                 
                    sitem.pickdateType==0?this.setState({ visible_0: true }):this.setState({ visible_1: true })}
                  }
                  key={index}
                  initValue={sitem.initValue}
                  label={sitem.label}
                  placeholder={sitem.placeholder}
                  inputName={sitem.inputName}
                  changeText={this._changeText}
                  disabled={true}
                  iconClass={sitem.iconClass}
                  inputType={sitem.inputType}
                />
           </DatePicker>;

          case "InputItem":
          return sitem.isShow==1?<TextInput
            key={index}
            initValue={sitem.initValue}
            label={sitem.label}
            placeholder={sitem.placeholder}
            inputName={sitem.inputName}
            changeText={this._changeText}
            disabled={sitem.disabled?sitem.disabled:false}
            iconClass={sitem.iconClass}
            inputType={sitem.inputTyp }
          />:null;
          case "PickInputItem":
               if(sitem.inputName=="yongCheXz"){
                return <Picker 
                key={index}
                 extra="请选择"
                data={sitem.pickerItems}
                title={sitem.label}
                value={[this.state.yongCheXzIndex]}
                cols={1}
                onOk={(e)=>this.onOk(e,sitem.inputName)}
                onDismiss={this._onDismiss}
              >
                  <List.Item arrow="horizontal" onClick={this.onClick}><span style={{"fontSize":'14px' ,"color": "#5e5e5e"}}>用车性质</span></List.Item>
               </Picker>
               }else{
                return <Picker   key={index}  extra="请选择"
                data={sitem.pickerItems}
                title={sitem.label}
                value={[this.state.applyQyIdIndex]}
                cols={1}
                onOk={(e)=>this.onOk(e,sitem.inputName)}
                onDismiss={this._onDismiss}
              >
                 <List.Item  arrow="horizontal" onClick={this.onClick}><span style={{"fontSize":'14px' ,"color": "#5e5e5e"}}>用车区域</span></List.Item>
               </Picker>
               }
       
               
             
               
         }
       })
    } 
   
  
  return (
    <div className="apply-container" key={index}>
         <div className="form-top">
             <span className={["form-top-icon","form-top-icon_"+topBar.icon].join("  ")}></span>
                   <span className="form-top-title">{topBar.title}</span>
              </div>
              <div className="form-item">
                    {inputType}
              </div>
       </div>
    )
  }


  _changeText({text,inputName}){
     console.log({value:text,name:inputName})
     let postData=this.state.postData;
     postData.map((item,index)=>{
          if(item.name==inputName){
             item.value=text;
          }
     })
     this.setState({
        postData
     })
    console.log(postData);
  }
  componentDidMount(){
    let user=JSON.parse(sessionStorage.user)//this.props.user;
    let param='&userDeptId='+user.userDeptId+'&id='+user.id+'&userPhone='+user.userPhone+'&userType='+user.userType;
    console.log(api.aplllyBase+param);
    axios.get(api.aplllyBase+param)
    .then(respone=>{
      console.log("---->",respone);
   
      if(respone.result&&respone.result=="ok"){
          let data=respone.data;
          // data.userDeptId
          // userDeptIdName
         
          let {userDeptIdName,userDeptId,fwDeptID,fwDeptIDName}=data.params
         let autoSetting= data.autoSetting;
         let {sxrDuanhaoFlag,
          sxrNameFlag,
          sxrPhoneFlag,
          ycrDuanhaoFlag,
          ycrNameFlag,
          ycrPhoneFlag}={sxrDuanhaoFlag:0,
            sxrNameFlag:1,
            sxrPhoneFlag:1,
            ycrDuanhaoFlag:0,
            ycrNameFlag:1,
            ycrPhoneFlag:1}
          if(autoSetting.length>0){
            sxrDuanhaoFlag=autoSetting[0]["sxrDuanhaoFlag"]
              sxrNameFlag=autoSetting[0]["sxrNameFlag"],
              sxrPhoneFlag=autoSetting[0]["sxrPhoneFlag"],
              ycrDuanhaoFlag=autoSetting[0]["ycrDuanhaoFlag"],
              ycrNameFlag=autoSetting[0]["ycrNameFlag"],
              ycrPhoneFlag=autoSetting[0]["ycrPhoneFlag"];
          }
          
           let {surplusCarTypeCount,trafficArea,carQuality}=data;
         
     
           let fromItems=this.state.fromItems;
           fromItems[0]['list']=[];

           fromItems[0]['list'].push({
              type: "InputItem",
              inputName:'yongCheRen',
              label: '用车人',
              icon:"",
              initValue:'', 
               text: "", 
               placeholder: '请填写您的真实姓名',
               isStar: false,
               isReset:true,
               isShow:ycrNameFlag
            });
            fromItems[0]['list'].push({  isShow:ycrPhoneFlag,type: "InputItem",inputName:'applyUsePhone', label: '用车人电话',initValue:'', icon: "", text: "", placeholder: '请填写用车人电话', isStar: false ,isReset:true});
            fromItems[0]['list'].push({ isShow:ycrDuanhaoFlag,type: "InputItem",inputName:'applyDuanhao', label: '用车人短号', initValue:'',icon: "", text: "", placeholder: '请填写用车人短号', isStar: false  ,isReset:true});
            fromItems[0]['list'].push({isShow:sxrNameFlag, type: "InputItem",inputName:'suiXingName', label: '随行人员', initValue:'',icon: "", text: "", placeholder: '请填写随行人员', isStar: false  ,isReset:true});
            fromItems[0]['list'].push({ isShow:sxrPhoneFlag,type: "InputItem",inputName:'suiXingPhone', label: '随行人员电话', initValue:'',icon: "", text: "", placeholder: '请填写随行人员电话', isStar: false  ,isReset:true});
            fromItems[0]['list'].push({ isShow:sxrDuanhaoFlag,type: "InputItem",inputName:'suiXingCall', label: '随行人员短号', initValue:'',icon: "", text: "", placeholder: '请填写随行人员短号', isStar: false  ,isReset:true});
            fromItems[0]['list'].push({ isShow:1,type: "InputItem",inputName:'applyManNum', label: '乘车人数', initValue:'',icon: "", text: "", placeholder: '请填写乘车人数', isStar: false  ,isReset:true});


           fromItems[1]['list'][0]['initValue']=userDeptIdName;
           let arr=[];
           if(carQuality&&carQuality.length>0){
             carQuality.map((item,index)=>{
              arr.push({
                value:index,
                label:item.qualityName
              });
            })
           }else{
             arr=[
              { value: 0, label: '随.省级领导调研用车' },
              { value: 1, label: '省级领导调研用车' },
              { value: 2, label: '省级领导调研用车' },
              { value: 3, label: '接待用车' },
              { value: 4, label: '重要公务用车' },
              { value: 5, label: '交通区域外用车' },
              { value: 6, label: '重要会议及大型活动用车' },
              { value: 7, label: '机要用车' },
              { value: 8, label: '应急用车' },
              { value: 9, label: '其他用车' }
            ]
           }
           fromItems[1]['list'][1]['pickerItems']=arr;
           this.state.yongCheXz=arr[0].label;
           fromItems[1]['list'][1]["text"]=arr[0].label;
           fromItems[1]['list'][7]['initValue']=fwDeptIDName;

         
           let areaArr=[];
            trafficArea.map((item,index)=>{
              areaArr.push({
                value:item.id,
                label:item.itemName
              })
           })
           fromItems[1]['list'][6].pickerItems=areaArr
           let carList=[];
           surplusCarTypeCount.map((item,index)=>{
            carList.push({
              type:'RadioItem',
              label:item.carTypeName+"("+item.cont+")",
              placeholder:'请填写用车数量',
              isCheck:false,
              id:item.id,
              carName:item.carTypeName,
              count:''

            });
           })
            fromItems[2]['list']=carList;
          //  this. {type:'RadioItem',label:'中型客车20',placeholder:'请填写用车数量'},
            this.setState({
              fromItems,
              userDeptId,
              fwDeptID,
              applyQyId:areaArr[0].value,
              autoSetting:data.autoSetting[0]
            })
            console.log(this.state.fromItems);
        }else{
          if(respone.msg&&respone.msg!=""){
            alert("用户没有权限");
            this.props.history.go(-1) 
          }else{
            alert("用户没有权限");
            this.props.history.go(-1) 
          }
           
          console.log(respone);
        }
     
    }).catch(err=>{
    
       console.log(err);
    })
  }
  postApply(){
    
    let user=JSON.parse(sessionStorage.user)
    var formData = new FormData();
   let postData=this.state.postData;
    let autoSetting=this.state.autoSetting;
    console.log("postData",postData);
    if(!StringUtils.isNotBlank(postData[0].value)&&autoSetting.ycrNameFlag==1){
       return  alert(postData[0].checkInfo);
    }
    if(!StringUtils.isNotBlank(postData[1].value)&&autoSetting.ycrPhoneFlag==1){
      return alert(postData[1].checkInfo);
    }
    if(!PhoneUtils.isPhoneNum(postData[1].value)&&autoSetting.ycrPhoneFlag==1){
      return alert("手机号格式有误，请重新输入");
    }
    if(!StringUtils.isNotBlank(postData[2].value)){
      return alert(postData[2].checkInfo);
    }
    // if(!StringUtils.isNotBlank(postData[8].value)&&autoSetting.ycrDuanhaoFlag==1){
    //   return alert(postData[8].checkInfo);
    // }
    if(!StringUtils.isNotBlank(postData[9].value)&&autoSetting.sxrNameFlag==1){
      return alert(postData[9].checkInfo);
    }
    if(!PhoneUtils.isPhoneNum(postData[10].value)&&autoSetting.sxrPhoneFlag==1){
      return alert("手机号格式有误，请重新输入");
    }
    // if(!StringUtils.isNotBlank(postData[11].value)&&autoSetting.sxrDuanhaoFlag==1){
    //   return alert(postData[11].checkInfo);
    // }
   


   if(!StringUtils.isNotBlank(this.state.userDeptId)){
    return alert("用车单位不能为空");
    }

    if(!StringUtils.isNotBlank(this.state.yongCheXz)){
      return alert("用车性质不能为空");
    }
    if(!StringUtils.isNotBlank(postData[3].value)){
      return alert(postData[3].checkInfo);
    }
    if(!StringUtils.isNotBlank(postData[4].value)){
      return alert(postData[4].checkInfo);
    }

    if(!StringUtils.isNotBlank(postData[5].value)){
      return alert(postData[5].checkInfo);
    }
    if(!StringUtils.isNotBlank(postData[6].value)){
      return alert(postData[6].checkInfo);
    }
    if(!StringUtils.isNotBlank(this.state.applyQyId)){
      return alert("用车区域不能为空");
    }
    if(!StringUtils.isNotBlank(postData[7].value)){
      return alert(postData[7].checkInfo);
    }
    let carArr=[];
    let count=0;
    this.state.fromItems[2]['list'].map((item,index)=>{
        if(item.isCheck){
          count=item.count;
          console.log(item);
          let str='{"'+item.carName+'":"'+item.count+'"}';
        
          carArr.push(str)
        }
    })
    if(carArr.length<=0){
      return alert("请选择用车种类");
    }
    if(count<=0){
      return alert("用车数量不能小于1辆车");
    }
      
   
    //console.log(new FormData());
    //当前登录用户的id
    formData.append("applyNameId",user.id);
    //当前登录用户的电话
    formData.append("applyNamePhone",user.userPhone);
    //用车人
    if(postData[0].value!="")
    formData.append("yongCheRen",postData[0].value);
    //用车人的电话
    if(postData[1].value!="")
    formData.append("applyUsePhone",postData[1].value);
    
    if(postData[8].value!="")
     formData.append("applyDuanhao",postData[8].value);
    if(postData[9].value!="")
     formData.append("suiXingName",postData[9].value);
     if(postData[10].value!="")
    formData.append("suiXingPhone",postData[10].value);
    if(postData[11].value!="")
    formData.append("suiXingCall",postData[11].value);




    //坐车人数
    formData.append("applyManNum",postData[2].value);
   //当前登录用户的部门id  用车单位
     formData.append("applyDeptId",this.state.userDeptId);
    //用车性质
    formData.append("yongCheXz",this.state.yongCheXz);
    //开始时间
    formData.append("applyUseTime",postData[3].value);
    //结束时间
    formData.append("applyBackTime",postData[4].value);
    //起点
    formData.append("applyUseAddress",postData[5].value);
    //终点
    formData.append("applyDestination",postData[6].value);
    //用车区域的ID
    formData.append("applyQyId",this.state.applyQyId);
    //服务中心的id
    formData.append("applyFwzxId",this.state.fwDeptID);
    //用车事由
    formData.append("applyRemark",postData[7].value);
    //用车备注
    formData.append("applyBz",this.state.applyBz);
    //用车种类
    formData.append("applySxPeople",JSON.stringify(carArr));
    // formData.forEach((item,index)=>{
    //   console.log("formData",item);
    // })
   axios.post(api.aplllyPost,formData)
      .then(respone => {
        console.log(respone);
     
        if (respone.result && respone.result == "ok") {
          alert('申请成功');
          this.props.history.go(-1) 
        } else {
          if(respone.msg&&respone.msg!=""){
            alert(respone.msg);
          }else{
            alert('申请成功');
          }
         
        }
      }).catch(err => {
      
        alert('申请失败');
      
        console.log(err);
      })
  }
  resetAction(){
    this.props.history.go(0) 
  }
  textareaChage(e){

     let  textarea=e.target.value;
     this.setState({applyBz:textarea});
    
   }
  render(){  
  
     return(
       <div className="apply">

          
             <Header 
              isBack={true}
              history={this.props.history}
              rightButtonView={null}
             />
             <div className="body">

            
                <div className="line-white"></div>
                  {this.state.fromItems.map((item,index)=>{
                    return this.renderItem(item,index)
                  })}
                <div className="textarea-conatiner">
                    <textarea 
                    onChange={this.textareaChage}
                    className="textarea"
                    placeholder="备注信息"/>
                </div>
                <div className="btn-group">
                   <Button
                    title={"申请"}
                    action={this.postApply}
                   />
                    <Button
                    title={"重置"}
                    action={this.resetAction}
                    style={{marginLeft:'10px',background:'#f68d06'}}
                   />
              </div>
             </div>
             
          </div>
      )
  }
}

const  mapStateToProps = (state, ownProps) => {
  return {

    user: state.user
 
 
  }
}
const actionCreators= {} ;
Apply=connect(mapStateToProps,actionCreators)(Apply)
export default  Apply
